package com.sxf.controller.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.cache.CacheManager;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.sxf.common.tools.NativeThreadLocal;
import com.sxf.domain.viewbean.UserVO;
import com.sxf.web.WebHelp;

/**
 * 权限拦截器 <br>
 * 分别实现预处理、后处理（调用了Service并返回ModelAndView，但未进行页面渲染）、返回处理（已经渲染了页面）
 * 在preHandle中，可以进行编码、安全控制等处理； 在postHandle中，有机会修改ModelAndView；
 * 在afterCompletion中，可以根据ex是否为null判断是否发生了异常，进行日志记录。 参数中的Object handler是下一个拦截器。
 * 
 * @author phsxf01
 */
public class PrivilegeInterceptor extends HandlerInterceptorAdapter {
	// @Resource(name = "memcachedClient")
	// private MemcachedClient memcachedClient;
	@Resource(name = "memCacheManager")
	private CacheManager cm;

	// 生成视图之前执行(Action):
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		UserVO user = WebHelp.getSessionUser(request, response, cm);
		if (user != null) {
			NativeThreadLocal.set(user);
		} else {
			response.sendRedirect(request.getContextPath() + "/blog/login");
			// throw new KickedOutException("请登录");
			return false;
		}
		return super.preHandle(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		if (ex != null) {
			ex.printStackTrace();
		}
		super.afterCompletion(request, response, handler, ex);
	}
}
